<template>
  <view class="qxlj_back4 contain">
    <!-- 头像 -->
    <view class="textareaBox">
      <view class=""><text>{{$t('userInfo.edit.avatar')}}</text></view>
      <view class="imgBox">
        <view class="imgMenu" v-if="imgList.length > 0">
          <view class="renderImg">
            <image :src="imgList[0]" mode="aspectFill" @click="previewImg(imgList[0])"></image>
          </view>
        </view>
        <view class="imgMenu upload-btn" @click="chooseImg()">
          <image src="https://wzws.wanshanlundiao.cn/upload/img/20250515/202505151713056097.png" mode="aspectFit"></image>
        </view>
      </view>
      <view class="note_head">{{$t('userInfo.edit.uploadNote')}}</view>
    </view>

    <!-- 个人信息 -->
    <view class="con_top">
      <view class="con_name">
        <view class="left">
          <text>{{$t('userInfo.edit.username')}}：</text>
        </view>
        <view class="right">
          <u--input :placeholder="$t('userInfo.edit.usernamePlaceholder')" border="none" v-model="name"></u--input>
        </view>
      </view>
      <view class="con_name">
        <view class="left">
          <text>{{$t('userInfo.edit.gender')}}：</text>
        </view>
        <view class="right" @click="sexShow=true">
          <text>{{sexValue}}</text>
          <u-picker @cancel='sexShow=false' @confirm="confirmSex()" :show="sexShow" :columns="columns"
                    keyName="value"></u-picker>
        </view>
      </view>
      <view class="con_name con_tel">
        <view class="left">
          <text>{{$t('userInfo.edit.birthday')}}：</text>
        </view>
        <view class="right" @click="showDay=true">
          <text>{{labalValue}}</text>
          <u-datetime-picker ref="datetimePicker" @cancel='showDay=false' @confirm="confirmDay()"
                             :show="showDay" v-model="DayValue" mode="date" :minDate="minDate"></u-datetime-picker>
        </view>
      </view>
    </view>
    <view class="btn_box">
      <button @click="submit" >{{$t('userInfo.edit.save')}}</button>
    </view>
  </view>
</template>

<script>
import {
  getUserinfoModify
} from '@/api/qxlj.js';
import Config from '@/config/index.js'
export default {
  data() {
    return {
      imgList: [],
      name: '',
      briday: '',
      sexShow: false,
      columns: [],
      sexID: '0',
      sexValue: '',
      showDay: false,
      DayValue: Number(new Date()),
      minDate: Number(new Date('1940-01-01')),
      labalValue: this.formatter(new Date()),
    }
  },
  computed: {
    // 计算性别选项
    genderColumns() {
      return [
        [{
          value: this.$t('userInfo.edit.genderOptions.secret'),
          ID: 0,
        },
          {
            value: this.$t('userInfo.edit.genderOptions.male'),
            ID: 1,
          },
          {
            value: this.$t('userInfo.edit.genderOptions.female'),
            ID: 2,
          }
        ]
      ]
    }
  },
  watch: {
    // 监听语言变化，更新性别选择器
    '$i18n.locale'() {
      this.updateColumns()
      this.updateSexValue()
      // 更新导航栏标题
      uni.setNavigationBarTitle({
        title: this.$t('userInfo.edit.title')
      })
    }
  },
  onLoad() {
    this.updateColumns()
    // 设置导航栏标题
    uni.setNavigationBarTitle({
      title: this.$t('userInfo.edit.title')
    })
    const user = this.$store.state.base.userInfo
    this.name = user.Name;
    this.imgList.push(user.HeadImg);
    if (user.Birthday != null) {
      this.labalValue = this.formatter(user.Birthday);
    }
    this.sexID = user.Sex;
    this.updateSexValue()
  },
  methods: {
    // 更新性别选择器列
    updateColumns() {
      this.columns = this.genderColumns
    },
    // 更新性别显示值
    updateSexValue() {
      if (this.sexID === 0) {
        this.sexValue = this.$t('userInfo.edit.genderOptions.secret')
      } else if (this.sexID === 1) {
        this.sexValue = this.$t('userInfo.edit.genderOptions.male')
      } else if (this.sexID === 2) {
        this.sexValue = this.$t('userInfo.edit.genderOptions.female')
      }
    },
    submit() {
      this.postData();
    },
    //提交数据
    async postData() {
      this.$store.dispatch("modifyUserInformation", {
        name: this.name,
        sexID: this.sexID,
        imgList: this.imgList[0],
        labelValue: this.labalValue,
      })
    },
    formatter(timestamp) {
      var date = new Date(timestamp);
      var Y = date.getFullYear() + '-';
      var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
      var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
      return Y + M + D;
    },
    chooseImg() {
      let _this = this;
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: function(res) {
          uni.uploadFile({
            url: Config.baseUrl + '/API/Users/PictureUpload',
            filePath: res.tempFilePaths[0],
            name: 'file',
            success: (uploadFileRes) => {
              let imgList = JSON.parse(uploadFileRes.data);
              _this.imgList = [imgList.picturePath]; // 直接替换第一张图片
            }
          });
        }
      });
    },
    previewImg(e) { //图片预览
      uni.previewImage({
        urls: [e],
        longPressActions: {
          itemList: [
            this.$t('userInfo.edit.preview.send'), 
            this.$t('userInfo.edit.preview.saveImage'), 
            this.$t('userInfo.edit.preview.favorite')
          ],
          success: function (data) {
            console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
          },
          fail: function (err) {
            console.log(err.errMsg);
          }
        }
      });
    },
    //选择性别
    confirmSex(e) {
      this.sexID = e.value[0].ID;
      this.sexValue = e.value[0].value;
      this.sexShow = false;
    },
    //选择生日
    confirmDay(e) {
      this.labalValue = this.formatter(e.value);
      this.showDay = false;
    },
  },
}
</script>

<style lang="scss" scoped>
.contain {
  width: 100%;
  min-height: 100vh;
  padding: 20rpx;
}

.textareaBox {
  padding: 0 30rpx 30rpx;
  background-color: #fff;
  border-radius: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
  margin-bottom: 20rpx;

  text {
    display: block;
    height: 80rpx;
    line-height: 80rpx;
    color: #333;
    font-weight: 600;
    font-size: 32rpx;
    margin-bottom: 20rpx;
  }
}

.imgBox {
  width: 100%;
  display: flex;
  align-items: center;
  gap: 30rpx;
  padding: 20rpx 0;

  .imgMenu {
    width: 116rpx;
    height: 116rpx;
    position: relative;
    background: #f5f5f5;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 12rpx;
    transition: all 0.3s ease;
    overflow: hidden;

    &:active {
      transform: scale(0.98);
    }

    .renderImg {
      width: 100%;
      height: 100%;
      border-radius: 12rpx;
      overflow: hidden;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

      image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    &.upload-btn {
      background: #f8f8f8;
      border: 2rpx dashed #ddd;

      image {
        width: 50rpx;
        height: 40rpx;
        opacity: 0.8;
      }
    }
  }
}

.note_head {
  font-size: 24rpx;
  color: #999;
  margin-top: 30rpx;
  padding: 0 10rpx;
}

.con_top {
  background-color: #fff;
  border-radius: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
  overflow: hidden;

  .con_name {
    padding: 0 30rpx;
    width: 100%;
    height: 100rpx;
    display: flex;
    align-items: center;
    color: #333;
    border-bottom: 1rpx solid #f5f5f5;
    font-size: 30rpx;
    transition: all 0.3s ease;

    &:active {
      background-color: #f8f8f8;
    }

    .left {
      width: 30%;
      color: #666;
    }

    .right {
      width: 70%;
      text-align: left;
      color: #333;
    }
  }

  .con_tel {
    border-bottom: none;
  }
}

.btn_box {
  margin-top: 20rpx;

  button{
    height: 86rpx;
    background: linear-gradient(135deg, #498FFF 0%, #3A7FE6 100%);
    color: #FFFFFF;
    font-size: 32rpx;
    font-weight: 500;
    border-radius: 44rpx;
    transition: all 0.3s ease;
    letter-spacing: 2rpx;

    &:active {
      transform: translateY(2rpx);
      box-shadow: 0 2rpx 8rpx rgba(73,143,255,0.2);
    }
  }
}
</style>